/*
   Copyright (C) 2007 Yen-Ju Chen <yjchenx gmail>

   This application is free software; you can redistribute it and/or 
   modify it under the terms of the MIT license. See COPYING.

*/

#import "AddressBookFactory.h"
#import "ABObject.h"

@implementation AddressBookFactory
/* Private */
- (ABObject *) _objectFromABPerson: (ABPerson *) person
{
	ABObject *object = [[ABObject alloc] init];
	int i, count = [_properties count];
	for (i = 0; i < count; i++)
	{
		NSString *property = [_properties objectAtIndex: i];
		id value = [person valueForProperty: property];
		if (value)
		{
			[object setValue: value forProperty: property];
		}
	}
	return AUTORELEASE(object);
}

- (OKGroup *) _groupFromABGroup: (ABGroup *) g
{
	OKGroup *group = [[OKGroup alloc] init];

	/* We keep the group empty until it is selected */
	[group setValue: [g valueForProperty: kABGroupNameProperty]
	       forProperty: kOKGroupNameProperty];
	[group setValue: [g valueForProperty: kABUIDProperty]
	       forProperty: kABUIDProperty];
	
	return AUTORELEASE(group);
}

/* Action */
- (IBAction) saveAddressBook: (id) sender
{
	NSLog(@"Save Address Book");
}

/* End of Private */
- (void) willDisplayGroup: (OKGroup *) group;
{
	if ([[group objects] count] == 0)
	{
		/* We rebuild the group */
		ABRecord *record = [_ab recordForUniqueId: [group valueForProperty: kABUIDProperty]];
		if ([record isKindOfClass: [ABGroup class]])
		{
			NSEnumerator *e = [[(ABGroup *)record members] objectEnumerator];
			ABPerson *person = nil;
			while ((person = [e nextObject]))
			{
				/* Find the person */
				NSEnumerator *ee = [[[self rootGroup] objects] objectEnumerator];
				OKObject *object = nil;
				while ((object = [ee nextObject]))
				{
					if ([[person uniqueId] isEqualToString: [object valueForProperty: kABUIDProperty]])
					{
						[group addObject: object];
						break;
					}
				}
			}
		}
		else
		{
			NSLog(@"Internal Error: %@ is not a ABGroup", group);
		}
	}
}

- (OKGroup *) rootGroup
{
	return _rootGroup;
}

- (NSArray *) propertiesToDisplay
{
	if (_propertiesToDisplay == nil)
	{
		_propertiesToDisplay = [[NSArray alloc] initWithObjects:
	        kABLastNameProperty,
			kABFirstNameProperty,
			nil];
	}
	return _propertiesToDisplay;
}

- (unsigned int) viewableMask
{
    return KRFactoryItemViewableMask | KRFactoryContentViewableMask;
}

- (NSArray *) collectionMenuItems
{
	if (_collectionMenuItems == nil)
	{
		_collectionMenuItems = [[NSMutableArray alloc] init];
		id <NSMenuItem> item = [[NSMenuItem alloc] initWithTitle: @"Save AddressBook"
		                                            action: @selector(saveAddressBook:)
		                                            keyEquivalent: @""];
		[item setTarget: self];
		[_collectionMenuItems addObject: item];
		DESTROY(item);
	}
	return _collectionMenuItems;
}

/* NSMenu */

- (BOOL) validateMenuItem: (id <NSMenuItem>) menuItem
{
	if ([menuItem action] == @selector(saveAddressBook:))
	{
		return [_ab hasUnsavedChanges];
	}
	return YES;
}

/* NSObject */
- (id) init
{
	self = [super init];

	/* Build up root group */
	_rootGroup = [[OKGroup alloc] init];
	_ab = [ABAddressBook sharedAddressBook];
	_properties = [[NSArray alloc] initWithObjects:
		kABUIDProperty,
		kABLastNameProperty,
		kABFirstNameProperty,
		nil];
	NSEnumerator *e = [[_ab people] objectEnumerator];
	ABPerson *person = nil;
	while ((person = [e nextObject]))
	{
		[_rootGroup addObject: [self _objectFromABPerson: person]];
	}

	e = [[_ab groups] objectEnumerator];
	ABGroup *group = nil;
	while ((group = [e nextObject]))
	{
		[_rootGroup addSubgroup: [self _groupFromABGroup: group]];
	}

	[_rootGroup setValue: @"AddressBook" forProperty: kOKGroupNameProperty];

	return self;
}

- (void) dealloc
{
	DESTROY(_rootGroup);
	DESTROY(_properties);
	DESTROY(_propertiesToDisplay);
	DESTROY(_collectionMenuItems);
	[super dealloc];
}

@end

